package com.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.platform.entity.*;
import com.platform.service.OrderGoodsService;
import com.platform.service.OrderService;
import com.platform.service.UserService;
import com.platform.utils.*;
import com.platform.utils.excel.ExcelExport;
import com.platform.vo.OrderDetailVo;
import com.platform.vo.OrderExportVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-08-13 10:41:09
 */
@RestController
@RequestMapping("order")
public class OrderController {
    private final static Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderGoodsService orderGoodsService;

    @Autowired
    private UserService userService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("order:list")
    public R list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);

        List<OrderEntity> orderList = orderService.queryList(query);
        int total = orderService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(orderList,total,query.getLimit(),query.getPage());
        return R.ok().put("page", pageUtil);
    }

    /**
     * 订单导出
     *
     * @param params
     * @param response
     * @return
     */
    @RequiresPermissions("order:export")
    @RequestMapping(value = "/exportExcel")
    @ResponseBody
    public R exportExcel(@RequestParam Map<String, Object> params,HttpServletResponse response) throws Exception {
        // 查询列表数据
        List<OrderEntity> orderExportList = orderService.queryList(params);

        ExcelExport ee = new ExcelExport("订单列表");

        String[] header = new String[]{"订单号", "会员", "订单类型", "订单状态", "发货状态","快递公司", "快递单号","收货省份", "实际支付金额", "订单总价", "商品总价", "商品名称", "商品规格", "商品图片", "下单时间"};

        List<Map<String, Object>> list = new ArrayList<>();

        if (!CollectionUtils.isEmpty(orderExportList)) {
            for (OrderEntity orderEntity : orderExportList) {
                OrderExportVo vo = new OrderExportVo();
                org.springframework.beans.BeanUtils.copyProperties(orderEntity, vo);
                setOrderStatus(vo);
                LinkedHashMap<String, Object> map = new LinkedHashMap<>();
                map.put("orderSn", vo.getOrderSn());
                UserEntity userEntity = userService.queryObject(vo.getUserId());
                map.put("username", null == userEntity ? null : userEntity.getUsername());
                //map.put("orderTypeStr", vo.getOrderTypeStr());
                map.put("orderStatusStr", vo.getOrderStatusStr());
                map.put("shippingStatusStr", vo.getShippingStatusStr());
                //map.put("payStatusStr", vo.getPayStatusStr());
                map.put("shippingName", vo.getShippingName());
                map.put("shippingNo", vo.getShippingNo());
                map.put("province",vo.getProvince());
                map.put("actualPrice", vo.getActualPrice());
                map.put("orderPrice", vo.getOrderPrice());
                map.put("goodsPrice", vo.getGoodsPrice());
                map.put("payTime", vo.getPayTime());
                list.add(map);
            }
        }
         ee.addSheetByMap("订单列表", list, header);
        ee.export(response);
        return R.ok();
    }



    /**
     * 信息  (获取订单的详情信息)
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("order:info")
    public R info(@PathVariable("id") Integer id) {
        logger.info("【请求开始】订单管理->所有管理->订单详情,请求参数:{}", JSONObject.toJSONString(id));
        OrderEntity order = orderService.queryObject(id);

        Map<String,Object> params = new HashMap<>();
        params.put("orderId",id);
        List<OrderGoodsEntity> orderGoods = orderGoodsService.queryList(params);
        Map<String,Object> map = new HashMap<>();
        map.put("order",order);
        map.put("orderGoods",orderGoods);

//        OrderDetailVo orderDetailVo = new OrderDetailVo();
//        BeanUtils.copyProperties(order,orderDetailVo);
//        //商品名称
//        String goodsName = "";
//        //商品规格详情
//        String goodsSpecifitionNameValue = "";
//        //商品数量
//        String goodsNum = "";
//        //商品图片
//        String listPicUrl = "";
//        for (OrderGoodsEntity orderGoodsEntity : list) {
//            goodsName=goodsName+orderGoodsEntity.getGoodsName()+",";
//            goodsNum= goodsNum+orderGoodsEntity.getNumber()+",";
//            if (orderGoodsEntity.getGoodsSpecifitionNameValue() != null){
//                goodsSpecifitionNameValue=goodsSpecifitionNameValue+orderGoodsEntity.getGoodsSpecifitionNameValue()+",";
//            }
//            if (orderGoodsEntity.getNumber() != null){
//                goodsNum +=orderGoodsEntity.getNumber()+",";
//            }
//            if (orderGoodsEntity.getListPicUrl()!=null){
//               listPicUrl += orderGoodsEntity.getListPicUrl()+",";
//            }
//        }
//
//        orderDetailVo.setAddress(order.getProvince()+order.getCity()+order.getDistrict()+order.getAddress());
//        orderDetailVo.setGoodsName(goodsName);
//        orderDetailVo.setGoodsSpecifitionNameValue(goodsSpecifitionNameValue);
//        orderDetailVo.setNumber(goodsNum);
//        orderDetailVo.setListPicUrl(listPicUrl);
        return R.ok().put("orderDetail", map);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("order:save")
    public R save(@RequestBody OrderEntity order) {
        orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("order:update")
    public R update(@RequestBody OrderEntity order) {
        orderService.update(order);

        return R.ok();
    }
    /**
     *
     * 修改订单价格
     */

    @RequestMapping("/updateOrder")
    public R updateOrder(@RequestBody OrderEntity order){
        orderService.updateOrder(order);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("order:delete")
    public R delete(@RequestBody Integer[] ids) {
        orderService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<OrderEntity> list = orderService.queryList(params);

        return R.ok().put("list", list);
    }

    /**
     * 总计
     */
    @RequestMapping("/queryTotal")
    public R queryTotal(@RequestParam Map<String, Object> params) {
        int sum = orderService.queryTotal(params);

        return R.ok().put("sum", sum);
    }

    /**
     * 确定收货
     *
     * @param id
     * @return
     */
    @RequestMapping("/confirm")
    @RequiresPermissions("order:confirm")
    public R confirm(@RequestBody Integer id) {
        orderService.confirm(id);

        return R.ok();
    }

    /**
     * 发货
     *
     * @param order
     * @return
     */
    @RequestMapping("/sendGoods")
    @RequiresPermissions("order:sendGoods")
    public R sendGoods(@RequestBody OrderEntity order) {
        orderService.sendGoods(order);

        return R.ok();
    }

    /**
     *
     * @param order
     * @return
     *
     */
    @RequestMapping("/selfCarry")
    //@RequiresPermissions("order:selfCarry")
    public R selfCarry(@RequestBody OrderEntity order) {
        orderService.selfCarry(order);

        return R.ok();
    }

    public void setOrderStatus(OrderExportVo vo) {
//        if (Constant.OrderTypeEnum.普通订单.getCode().equals(vo.getOrderType())) {
//            vo.setOrderTypeStr(Constant.OrderTypeEnum.普通订单.getMsg());
//        }else if(Constant.OrderTypeEnum.团购订单.getCode().equals(vo.getOrderType())){
//            vo.setOrderTypeStr(Constant.OrderTypeEnum.团购订单.getMsg());
//        }else if (Constant.OrderTypeEnum.砍价订单.getCode().equals(vo.getOrderType())){
//            vo.setOrderTypeStr(Constant.OrderTypeEnum.砍价订单.getMsg());
//        }else if (Constant.OrderTypeEnum.直接购买.getCode().equals(vo.getOrderType())){
//            vo.setOrderTypeStr(Constant.OrderTypeEnum.直接购买.getMsg());
//        }
        if (Constant.OrderStatusEnum.待付款.getCode().equals(vo.getOrderStatus())) {
            vo.setOrderStatusStr(Constant.OrderStatusEnum.待付款.getMsg());
        }else if(Constant.OrderStatusEnum.已取消.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.已取消.getMsg());
        }else if(Constant.OrderStatusEnum.已删除.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.已删除.getMsg());
        }else if(Constant.OrderStatusEnum.待发货.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.待发货.getMsg());
        }else if(Constant.OrderStatusEnum.已发货.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.已发货.getMsg());
        }else if(Constant.OrderStatusEnum.确认收货.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.确认收货.getMsg());
        }else if(Constant.OrderStatusEnum.自提.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.自提.getMsg());
        }else if(Constant.OrderStatusEnum.未发货退款.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.未发货退款.getMsg());
        }else if(Constant.OrderStatusEnum.已收货退款退货.getCode().equals(vo.getOrderStatus())){
            vo.setOrderStatusStr(Constant.OrderStatusEnum.已收货退款退货.getMsg());
        }

        if (Constant.ShipStatus.未发货.getCode().equals(vo.getShippingStatus())) {
            vo.setShippingStatusStr(Constant.ShipStatus.未发货.getMsg());
        }else if(Constant.ShipStatus.已发货.getCode().equals(vo.getShippingStatus())){
            vo.setShippingStatusStr(Constant.ShipStatus.已发货.getMsg());
        }else if(Constant.ShipStatus.已收货.getCode().equals(vo.getShippingStatus())){
            vo.setShippingStatusStr(Constant.ShipStatus.已收货.getMsg());
        }else if(Constant.ShipStatus.退货.getCode().equals(vo.getShippingStatus())){
            vo.setShippingStatusStr(Constant.ShipStatus.退货.getMsg());
        }

//        if (Constant.PayStatusEnum.未付款.getCode().equals(vo.getPayStatus())) {
//            vo.setPayStatusStr(Constant.PayStatusEnum.未付款.getMsg());
//        }else if(Constant.PayStatusEnum.付款中.getCode().equals(vo.getPayStatus())){
//            vo.setPayStatusStr(Constant.PayStatusEnum.付款中.getMsg());
//        }else if(Constant.PayStatusEnum.已付款.getCode().equals(vo.getPayStatus())){
//            vo.setPayStatusStr(Constant.PayStatusEnum.已付款.getMsg());
//        }
    }
   //取消订单
    @RequestMapping("/orderCancel/{orderId}")
    @RequiresPermissions("order:cancel")
    public R orderCancel(@PathVariable("orderId") Integer orderId){
        orderService.orderCancel(orderId);
        return R.ok();
    }

    /**
     * @param order 支付对账
     * @return
     */
    @RequestMapping(value = "/create", method = {RequestMethod.POST})
    public void wxpay(@RequestBody OrderEntity order) {
        try {
            String yesterday = "2020-9-24";
            String today = "2020-9-25";
            // 获取昨日、已支付、已完成、未对账的订单
            List<OrderEntity> orderList = orderService.selectAll(SqlParameter.getParameter()
                    .addQuery("stateList", "stateList")
                    .addQuery("start", yesterday)
                    .addQuery("end", today)
                    .addQuery("checkState",0)//未对账
                    .getMap());
            List<OrderEntity> orderListChark = orderService.selectAll(SqlParameter.getParameter()
                    .addQuery("stateList", "stateList")
                    .addQuery("start", yesterday)
                    .addQuery("end", today)
                    .addQuery("checkState", 1)//已对账
                    .getMap());
            if (orderList.size() > 0) {
                List<String> list1 = toStringList(orderList);
                Map<String, List<String>> contrast = WeChatUtils.contrast(list1);
                List<String> successOrderList = contrast.get("successOrderList");
                if (contrast.get("successOrderList").size() > 0) {
                    orderService.update((OrderEntity) SqlParameter.getParameter()
                            .addUpdate("pay_status", 4)
                            .addUpdate("checkState", 1)
                            .addQuery("orderList", successOrderList)
                            .getMap());
                }
                if (contrast.get("errorOrderList").size() > 0) {
                    orderService.update((OrderEntity) SqlParameter.getParameter()
                            .addUpdate("checkState", 1)
                            .addQuery("orderList", contrast.get("errorOrderList"))
                            .getMap());
                }

            }
           if (orderListChark.size() > 0) {
                List<String> list2 = toStringList(orderListChark);
                Map<String, List<String>> contrastChark = WeChatUtils.contrast(list2);
                if (contrastChark != null && contrastChark.get("successOrderList").size() > 0) {
                    orderService.update((OrderEntity) SqlParameter.getParameter()
                            .addUpdate("pay_status", 4)
                            .addUpdate("checkState", 1)//1已短对账
                            .addQuery("orderList", contrastChark.get("successOrderList"))
                            .getMap());
                }
                if (contrastChark != null && contrastChark.get("errorOrderList").size() > 0) {
                    orderService.update((OrderEntity) SqlParameter.getParameter()
                            .addUpdate("pay_status", 6)
                            .addUpdate("checkState", 2)//2已长对账
                            .addQuery("orderList", contrastChark.get("errorOrderList"))
                            .getMap());
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }

    }

    public List<String> toStringList(List<OrderEntity> list) {
        ArrayList<String> arrayList = new ArrayList<>();
        for (OrderEntity order : list) {
            arrayList.add(order.getNumber() + "%"+order.getId()+ order.getOrderPrice());
        }
        return arrayList;
    }


}

